﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

using Expo.Training.DataAccess.Member;
using Expo.Training.Entity;
using Expo.Training.DataAccess.Exam;
using Expo.Training.BRule.Exam;
using Expo.Training.BRule.Audit;
using Expo.Training.BRule.Member;
using Expo.Training.DataAccess.Vip;

using System.IO;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;

public partial class User_ManagementUser : PageBase
{
    public string xybcCustomerCode = System.Configuration.ConfigurationManager.AppSettings.Get("XYBCCustomerCode").ToLower();

    private string SortExpression
    {
        get
        {
            if (this.ViewState["SortExpression"] == null || this.ViewState["SortExpression"].ToString().Trim().Length == 0)
                this.ViewState["SortExpression"] = " RegDate DESC ";
            return this.ViewState["SortExpression"].ToString();
        }
        set
        {
            this.ViewState["SortExpression"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        InitSortButtons();
        if (!IsPostBack)
        {
            sup_SearchUserPanel.InitControl();
        }
        if (this.Customer.CustomerCode.ToLower() == xybcCustomerCode)
        {
            sup_SearchUserPanel.HideExcel = false;
        }
        else
        {
            sup_SearchUserPanel.HideExcel = true;
        }
    }

    public static bool IsNumeric(string itemValue)
    {
        try
        {
            int i = Convert.ToInt32(itemValue);
            return true;
        }
        catch
        {
            return false;
        }
    }

    protected void PageIndex_Changed(object sender, EventArgs e)
    {
        BindUser();
    }

    protected void BindUser()
    {
        cc_ExPager.PageSize = sup_SearchUserPanel.GetPageSize;
        sup_SearchUserPanel.SortExpression = this.SortExpression;

        int totalCount = 0;
        List<MemberEntity> mList = sup_SearchUserPanel.QueryUserList(cc_ExPager.PageIndex + 1, cc_ExPager.PageSize, out totalCount);

        if (mList != null && mList.Count > 0)
        {
            rpt_UserList.DataSource = mList;
            rpt_UserList.DataBind();
            cc_ExPager.TotalRecords = totalCount;

            dv_Result.Visible = true;
            dv_NoResult.Visible = false;
        }
        else
        {
            dv_Result.Visible = false;
            dv_NoResult.Visible = true;
        }
    }

    protected void DoSearch_Command(object sender, CommandEventArgs e)
    {
        cc_ExPager.PageIndex = 0;
        BindUser();
    }

    private void InitSortButtons()
    {
        this.exSBtn_CardID.CurrSortExpression = this.SortExpression;
        this.exSBtn_IDCard.CurrSortExpression = this.SortExpression;
        this.exSBtn_RealName.CurrSortExpression = this.SortExpression;
        this.exSBtn_RegDate.CurrSortExpression = this.SortExpression;
        this.exSBtn_Sex.CurrSortExpression = this.SortExpression;
    }

    protected void Sort_Changed(object sender, EventArgs e)
    {
        cc_ExPager.PageIndex = 0;
        this.SortExpression = ((LinkButton)sender).CommandArgument;
        InitSortButtons();
        BindUser();
    }

    protected void rpt_User_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "delete")
        {
            Guid memberId = new Guid(e.CommandArgument.ToString());
            string userAccount = ((HiddenField)(e.Item.FindControl("hid_UserAccount"))).Value;
            string realName = ((HiddenField)(e.Item.FindControl("hid_RealName"))).Value;

            //删除用户记录
            //Expo.Training.DataAccess.Member.Member.DeleteMember(memberId);

            Member_Info objMI = new Member_Info();
            objMI.MemberID = memberId;
            if (objMI.Exist())
            {
                objMI.Stutas = MemberConst.MEMBER_STATUS_DELETENOTAUDIT;
                objMI.Creator = this.Member.MemberID;
                objMI.PeriodDate = DateTime.Now;
                objMI.Update();
            }

            Audit.AuditLog(this.Member.MemberID, string.Format("{0}|{1}|{2},{3},{4}|{5}", "用户信息管理", "删除", userAccount, realName, "已删除", "成功"));
            //Customer_Access UserAccountLicence - 1
            //Customer_Access objCA = new Customer_Access();
            //objCA.CustomerID = this.Member.CustomerID;
            //if (objCA.Exist())
            //{
            //    objCA.UseAccountLicence = objCA.UseAccountLicence - 1;
            //    objCA.Update();
            //}

            //Modify 2014-10-15
            //增加同步至学分银行的逻辑
            //if (MemberAccess.DeleteMemberToBank("", this.Member.MemberID.ToString()) == "Fail")
            //{
            //    AddEndScript("del succes", "alert('数据同步失败！请联系管理员!');");
            //}
            BindUser();
            AddEndScript("del succes", "alert('删除用户成功，请等待管理员审核！');");
        }
    }

    protected string GetBGColor(object o_status)
    {
        switch (int.Parse(o_status.ToString()))
        {
            case MemberConst.MEMBER_STATUS_EXPIRED:
                return MemberConst.MEMBER_STATUS_BGCOLOR_EXPIRED;
            case MemberConst.MEMBER_STATUS_PAUSE:
                return MemberConst.MEMBER_STATUS_BGCOLOR_PAUSE;
            default:
                return MemberConst.MEMBER_STATUS_BGCOLOR_START;
        }
    }

    protected void btnBatchDelete_Click(object sender, EventArgs e)
    {
        foreach (RepeaterItem objRI in rpt_UserList.Items)
        {
            HtmlInputCheckBox ck_One = (HtmlInputCheckBox)objRI.FindControl("ck_One");
            HiddenField hdUserAccount = (HiddenField)objRI.FindControl("hid_UserAccount");
            HiddenField hdRealName = (HiddenField)objRI.FindControl("hid_RealName");
            if (ck_One.Checked)
            {
                Guid memberId = new Guid(ck_One.Value);
                string userAccount = hdUserAccount.Value;
                string realName = hdRealName.Value;

                Member_Info objMI = new Member_Info();
                objMI.MemberID = memberId;
                if (objMI.Exist())
                {
                    objMI.Stutas = MemberConst.MEMBER_STATUS_DELETENOTAUDIT;
                    objMI.Creator = this.Member.MemberID;
                    objMI.PeriodDate = DateTime.Now;
                    objMI.Update();
                }
                //Modify 2014-10-15
                //增加同步至学分银行的逻辑
                if (MemberAccess.DeleteMemberToBank("", this.Member.MemberID.ToString()) == "Fail")
                {
                    AddEndScript("del succes", "alert('数据同步失败！请联系管理员!');");
                }
                Audit.AuditLog(this.Member.MemberID, string.Format("{0}|{1}|{2},{3},{4}|{5}", "用户信息管理", "删除", userAccount, realName, "已删除", "成功"));

            }
        }
        BindUser();
        AddEndScript("del succes", "alert('删除用户成功，请等待管理员审核！');");
    }

    #region
    /// <summary>
    /// 导出列名
    /// </summary>
    public static System.Collections.SortedList ListColumnsName;

    /// <summary>
    /// 导出Excel
    /// </summary>
    /// <param name="dgv"></param>
    /// <param name="filePath"></param>
    public static void ExportExcel(DataTable dtSource, string filePath)
    {
        if (ListColumnsName == null || ListColumnsName.Count == 0)
            throw (new Exception("请对ListColumnsName设置要导出的列明！"));
        HSSFWorkbook excelWorkbook = CreateExcelFile();
        InsertRow(dtSource, excelWorkbook);
        SaveExcelFile(excelWorkbook, filePath);
    }
    
    /// <summary>
    /// 导出Excel
    /// </summary>
    /// <param name="dgv"></param>
    /// <param name="filePath"></param>
    public static void ExportExcel(DataTable dtSource, Stream excelStream)
    {
        if (ListColumnsName == null || ListColumnsName.Count == 0)
            throw (new Exception("请对ListColumnsName设置要导出的列明！"));
        HSSFWorkbook excelWorkbook = CreateExcelFile();
        InsertRow(dtSource, excelWorkbook);
        SaveExcelFile(excelWorkbook, excelStream);
    }
    
    /// <summary>
    /// 保存Excel文件
    /// </summary>
    /// <param name="excelWorkBook"></param>
    /// <param name="filePath"></param>
    protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, string filePath)
    {
        FileStream file = null;
        try
        {
            file = new FileStream(filePath, FileMode.Create);
            excelWorkBook.Write(file);
        }
        finally
        {
            if (file != null)
            {
                file.Close();
            }
        }
    }
    
    /// <summary>
    /// 保存Excel文件
    /// </summary>
    /// <param name="excelWorkBook"></param>
    /// <param name="filePath"></param>
    protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, Stream excelStream)
    {
        try
        {
            excelWorkBook.Write(excelStream);
        }
        finally
        {
        }
    }
    
    /// <summary>
    /// 创建Excel文件
    /// </summary>
    /// <param name="filePath"></param>
    protected static HSSFWorkbook CreateExcelFile()
    {
        HSSFWorkbook hssfworkbook = new HSSFWorkbook();
        return hssfworkbook;
    }
    
    /// <summary>
    /// 创建excel表头
    /// </summary>
    /// <param name="dgv"></param>
    /// <param name="excelSheet"></param>
    protected static void CreateHeader(HSSFSheet excelSheet)
    {
        int cellIndex = 0;
        //循环导出列
        foreach (System.Collections.DictionaryEntry de in ListColumnsName)
        {
            HSSFRow newRow = excelSheet.CreateRow(0);
            HSSFCell newCell = newRow.CreateCell(cellIndex);
            newCell.SetCellValue(de.Value.ToString());
            cellIndex++;
        }
    }
    
    /// <summary>
    /// 插入数据行
    /// </summary>
    protected static void InsertRow(DataTable dtSource, HSSFWorkbook excelWorkbook)
    {
        int rowCount = 0;
        int sheetCount = 1;
        HSSFSheet newsheet = null;
        
        //循环数据源导出数据集
        newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
        CreateHeader(newsheet);
        foreach (DataRow dr in dtSource.Rows)
        {
            rowCount++;
            
            //超出10000条数据 创建新的工作簿
            if (rowCount == 50000)
            {
                rowCount = 1;
                sheetCount++;
                newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
                CreateHeader(newsheet);
            }
            
            HSSFRow newRow = newsheet.CreateRow(rowCount);
            InsertCell(dtSource, dr, newRow, newsheet, excelWorkbook);
        }
    }
    
    /// <summary>
    /// 导出数据行
    /// </summary>
    /// <param name="dtSource"></param>
    /// <param name="drSource"></param>
    /// <param name="currentExcelRow"></param>
    /// <param name="excelSheet"></param>
    /// <param name="excelWorkBook"></param>
    protected static void InsertCell(DataTable dtSource, DataRow drSource, HSSFRow currentExcelRow, HSSFSheet excelSheet, HSSFWorkbook excelWorkBook)
    {
        for (int cellIndex = 0; cellIndex < ListColumnsName.Count; cellIndex++)
        {
            //列名称
            string columnsName = ListColumnsName.GetKey(cellIndex).ToString();
            HSSFCell newCell = null;
            System.Type rowType = drSource[columnsName].GetType();
            string drValue = drSource[columnsName].ToString().Trim();
            switch (rowType.ToString())
            {
                case "System.String"://字符串类型
                    drValue = drValue.Replace("&", "&");
                    drValue = drValue.Replace(">", ">");
                    drValue = drValue.Replace("<", "<");
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(drValue);
                    break;
                case "System.DateTime"://日期类型
                    DateTime dateV;
                    DateTime.TryParse(drValue, out dateV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(dateV);

                    //格式化显示
                    HSSFCellStyle cellStyle = excelWorkBook.CreateCellStyle();
                    HSSFDataFormat format = excelWorkBook.CreateDataFormat();
                    cellStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss");
                    newCell.CellStyle = cellStyle;
                    break;
                case "System.Boolean"://布尔型
                    bool boolV = false;
                    bool.TryParse(drValue, out boolV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(boolV);
                    break;
                case "System.Int16"://整型
                case "System.Int32":
                case "System.Int64":
                case "System.Byte":
                    int intV = 0;
                    int.TryParse(drValue, out intV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(intV.ToString());
                    break;
                case "System.Decimal"://浮点型
                case "System.Double":
                    double doubV = 0;
                    double.TryParse(drValue, out doubV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(doubV);
                    break;
                case "System.DBNull"://空值处理
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue("");
                    break;
                default:
                    throw (new Exception(rowType.ToString() + "：类型数据无法处理!"));
            }
        }
    }
    #endregion
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dtSource = sup_SearchUserPanel.QueryUserList();
        ListColumnsName = new SortedList();
        ListColumnsName.Add("RealName", "用户姓名");
        ListColumnsName.Add("IDCard", "证件号码");
        ListColumnsName.Add("UserAccount", "用户账号");
        ListColumnsName.Add("CardID", "学习卡号");
        ListColumnsName.Add("Duty", "工作单位");
        ListColumnsName.Add("CellPhone", "手机号");
        ListColumnsName.Add("RegDate", "创建日期");
        Response.Clear();
        Response.BufferOutput = false;
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        string filename = HttpUtility.UrlEncode(DateTime.Now.ToString("学员信息管理"));
        Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        Response.ContentType = "application/ms-excel";
        ExportExcel(dtSource, Response.OutputStream);
        Response.Close();
    }

    #region 批量升级VIP
    protected void btnBatchUpgrade_Click(object sender, EventArgs e)
    {
        foreach (RepeaterItem _item in rpt_UserList.Items)
        {
            HtmlInputCheckBox ck_One = (HtmlInputCheckBox)_item.FindControl("ck_One");
            HiddenField hdUserAccount = (HiddenField)_item.FindControl("hid_UserAccount");
            HiddenField hdRealName = (HiddenField)_item.FindControl("hid_RealName");
            if (ck_One.Checked)
            {
                Guid _memberId = new Guid(ck_One.Value);
                string userAccount = hdUserAccount.Value;
                string realName = hdRealName.Value;

                VipEntity _model = new VipEntity();
                _model = VipModule.GetVipByMemberID(_memberId);
                _model.UpgradeTime = DateTime.Now;
                _model.Category = 2;

                VipModule.UpdateVip(_model);

                //Audit.AuditLog(this.Member.MemberID, string.Format("{0}|{1}|{2},{3},{4}|{5}", "用户信息管理", "删除", userAccount, realName, "已删除", "成功"));

            }
        }
        BindUser();
        AddEndScript("upgrade succes", "alert('升级用户成功！');");
    }
    #endregion
}
